import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../providers/news_provider.dart';
import '../providers/todos_provider.dart';
import '../providers/settings_provider.dart';
import '../../utils/keyboard_utils.dart';

/// 综合实战App首页
/// 展示: Riverpod状态管理 + Dio网络请求 + rxDart搜索防抖
class ComprehensiveHomePage extends ConsumerStatefulWidget {
  const ComprehensiveHomePage({super.key});

  @override
  ConsumerState<ComprehensiveHomePage> createState() => _ComprehensiveHomePageState();
}

class _ComprehensiveHomePageState extends ConsumerState<ComprehensiveHomePage> {
  final TextEditingController _searchController = TextEditingController();

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final userSettings = ref.watch(userSettingsProvider);
    final totalTodos = ref.watch(totalTodosProvider);
    final activeTodos = ref.watch(activeTodosProvider);

    return DismissKeyboardScaffold(
      appBar: AppBar(
        title: const Text('综合实战 App'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            // 退出综合实战App，返回主应用
            // 需要使用根Navigator，跳过go_router的导航栈
            Navigator.of(context, rootNavigator: true).pop();
          },
          tooltip: '返回主应用',
        ),
        actions: [IconButton(icon: const Icon(Icons.settings), onPressed: () => context.push('/settings'))],
      ),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 欢迎卡片
            Card(
              color: Colors.purple.shade50,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('👋 欢迎, ${userSettings.username}!', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    const Text(
                      '这是一个综合示例应用，整合了：\n'
                      '• Riverpod - 状态管理\n'
                      '• go_router - 路由管理\n'
                      '• Dio - 网络请求\n'
                      '• rxDart - 响应式编程',
                      style: TextStyle(fontSize: 14),
                    ),
                    const SizedBox(height: 12),
                    const Divider(),
                    const SizedBox(height: 8),
                    const Row(
                      children: [
                        Icon(Icons.info_outline, size: 16, color: Colors.blue),
                        SizedBox(width: 8),
                        Expanded(
                          child: Text('点击左上角返回箭头可以退出综合实战模式', style: TextStyle(fontSize: 12, color: Colors.blue)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 待办事项快速入口
            Card(
              child: ListTile(
                leading: CircleAvatar(
                  backgroundColor: Colors.blue,
                  child: Text('$activeTodos', style: const TextStyle(color: Colors.white)),
                ),
                title: const Text('我的待办事项'),
                subtitle: Text('总共 $totalTodos 项，待完成 $activeTodos 项'),
                trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                onTap: () => context.push('/todos'),
              ),
            ),
            const SizedBox(height: 16),

            // 搜索框（使用rxDart防抖）
            TextField(
              controller: _searchController,
              decoration: InputDecoration(
                labelText: '搜索新闻（rxDart防抖演示）',
                hintText: '输入关键词...',
                prefixIcon: const Icon(Icons.search),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () {
                    _searchController.clear();
                    ref.read(searchControllerProvider).add('');
                  },
                ),
                border: const OutlineInputBorder(),
              ),
              onChanged: (value) {
                // 通过rxDart的BehaviorSubject发送搜索关键词
                ref.read(searchControllerProvider).add(value);
              },
            ),
            const SizedBox(height: 8),
            const Text('💡 提示：输入会在500ms后触发搜索（防抖）', style: TextStyle(fontSize: 12, color: Colors.grey)),
            const SizedBox(height: 16),

            // 搜索结果
            Consumer(
              builder: (context, ref, child) {
                final searchResultsAsync = ref.watch(searchResultsProvider);

                return searchResultsAsync.when(
                  data: (results) {
                    if (results.isEmpty && _searchController.text.isNotEmpty) {
                      return Card(
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Center(child: Text('未找到"${_searchController.text}"相关的新闻')),
                        ),
                      );
                    }

                    if (results.isNotEmpty) {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('搜索结果 (${results.length})', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                          const SizedBox(height: 8),
                          ...results.take(3).map((news) {
                            return Card(
                              child: ListTile(
                                title: Text(news.title, maxLines: 1, overflow: TextOverflow.ellipsis),
                                subtitle: Text(news.summary, maxLines: 2, overflow: TextOverflow.ellipsis),
                                trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                                onTap: () => context.push('/news/${news.id}'),
                              ),
                            );
                          }),
                        ],
                      );
                    }

                    return const SizedBox.shrink();
                  },
                  loading: () => const Card(
                    child: Padding(
                      padding: EdgeInsets.all(16),
                      child: Center(child: CircularProgressIndicator()),
                    ),
                  ),
                  error: (error, stack) => Card(
                    child: Padding(padding: const EdgeInsets.all(16), child: Text('搜索错误: $error')),
                  ),
                );
              },
            ),
            const SizedBox(height: 16),

            // 分类过滤
            const Text('新闻分类', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Consumer(
              builder: (context, ref, child) {
                final selectedCategory = ref.watch(selectedCategoryProvider);

                return Wrap(
                  spacing: 8,
                  children: ['全部', '科技', '财经', '生活'].map((category) {
                    final isSelected = selectedCategory == category || (selectedCategory == null && category == '全部');
                    return ChoiceChip(
                      label: Text(category),
                      selected: isSelected,
                      onSelected: (selected) {
                        ref.read(selectedCategoryProvider.notifier).state = category == '全部' ? null : category;
                      },
                    );
                  }).toList(),
                );
              },
            ),
            const SizedBox(height: 16),

            // 新闻列表（使用Dio获取）
            const Text('新闻列表（Dio网络请求）', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Consumer(
              builder: (context, ref, child) {
                final newsAsync = ref.watch(filteredNewsProvider);

                return newsAsync.when(
                  data: (newsList) {
                    if (newsList.isEmpty) {
                      return const Card(
                        child: Padding(
                          padding: EdgeInsets.all(32),
                          child: Center(child: Text('该分类暂无新闻')),
                        ),
                      );
                    }

                    return Column(
                      children: newsList.take(5).map((news) {
                        return Card(
                          child: ListTile(
                            leading: Container(
                              width: 60,
                              height: 60,
                              decoration: BoxDecoration(color: _getCategoryColor(news.category), borderRadius: BorderRadius.circular(8)),
                              child: Center(
                                child: Text(
                                  news.category,
                                  style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12),
                                ),
                              ),
                            ),
                            title: Text(news.title, maxLines: 2, overflow: TextOverflow.ellipsis),
                            subtitle: Text(news.summary, maxLines: 2, overflow: TextOverflow.ellipsis),
                            trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                            onTap: () => context.push('/news/${news.id}'),
                          ),
                        );
                      }).toList(),
                    );
                  },
                  loading: () => const Card(
                    child: Padding(
                      padding: EdgeInsets.all(32),
                      child: Center(child: CircularProgressIndicator()),
                    ),
                  ),
                  error: (error, stack) => Card(
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        children: [
                          const Icon(Icons.error, size: 48, color: Colors.red),
                          const SizedBox(height: 8),
                          Text('加载失败: $error'),
                          const SizedBox(height: 8),
                          ElevatedButton(
                            onPressed: () {
                              ref.invalidate(newsListProvider);
                            },
                            child: const Text('重试'),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Color _getCategoryColor(String category) {
    switch (category) {
      case '科技':
        return Colors.blue;
      case '财经':
        return Colors.green;
      case '生活':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }
}
